<template>
  <van-dialog v-model:show="loginShow" :show-confirm-button="false" style="height: 80vh">
    <div id="login">
      <div class="loginBox">
        <div class="auth-form">
          <van-tabs v-model:active="active" animated style="min-height: 15rem" @change="handleTabChange">
            <van-tab title="账号密码">
              <van-form>
                <van-cell-group style="margin-top: 1rem">
                  <van-field
                    v-model="loginUserName"
                    placeholder="请输入用户名"
                    required
                    style="line-height: 10vw"
                  />
                  <van-field
                    v-model="loginPassword"
                    :type="showPassword ? '' : 'password'"
                    placeholder="请输入密码"
                    required
                    style="line-height: 10vw"
                  />
                  <van-field
                    v-model="imgCaptcha"
                    center
                    clearable
                    maxlength="4"
                    placeholder="请输入验证码"
                    style="line-height: 10vw"
                  >
                    <template #button>
                      <img
                        :src="captchaUrl"
                        alt="captcha"
                        class="verificationImage"
                        @click.prevent="updateCaptchaUrl(LOGIN)"
                      />
                    </template>
                  </van-field>
                </van-cell-group>
              </van-form>
            </van-tab>
            <van-tab title="快捷登录">
              <van-form>
                <van-cell-group style="margin-top: 1rem">
                  <van-field
                    v-model="loginPhone"
                    :error-message="phoneNumberRight ? '' : '手机号格式不正确'"
                    clearable
                    maxlength="11"
                    placeholder="请输入手机号"
                    required
                    style="line-height: 10vw"
                  />
                  <van-field
                    v-model="imgCaptcha"
                    center
                    clearable
                    maxlength="4"
                    placeholder="请输入图形验证码"
                    required
                    style="line-height: 10vw"
                  >
                    <template #button>
                      <img
                        :src="captchaUrl"
                        alt="captcha"
                        class="verificationImage"
                        @click.prevent="updateCaptchaUrl(MSG_LOGIN + '_CAPTCHA')"
                      />
                    </template>
                  </van-field>
                  <van-field
                    v-model="smsCaptcha"
                    center
                    clearable
                    maxlength="6"
                    placeholder="请输入短信验证码"
                    style="line-height: 10vw"
                  >
                    <template #button>
                      <van-button
                        v-if="!countDown"
                        :disabled="captchaDisable"
                        class="verificationImage"
                        size="small"
                        type="primary"
                        @click="sendSmsCode"
                      >
                        发送
                      </van-button>
                      <van-button v-else class="verificationImage" size="small" type="primary">
                        {{ '已发送 ' + countDown }}
                      </van-button>
                    </template>
                  </van-field>
                </van-cell-group>
              </van-form>
            </van-tab>
          </van-tabs>
          <van-button
            :disabled="!loginValidate"
            block
            size="normal"
            style="margin-top: 1rem"
            type="primary"
            @click="login"
          >
            登录
          </van-button>
          <!-- 第三方登录 -->
          <template v-if="isInWx()">
            <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 0.8rem' }">
              其他登录方式
            </van-divider>
            <van-grid :border="false" :column-num="1">
              <van-grid-item @click="wechatLogin">
                <svg-icon name="wechat" />
                <div class="title">微信登录</div>
              </van-grid-item>
            </van-grid>
          </template>
          <!-- 底部声明 -->
          <p v-if="isShowSMSLogin" class="agreement">
            温馨提示：
            <br />
            未注册的手机号，登录时将自动注册，且代表同意
            <a class="agreement-box" @click.stop="agreement(0)">用户协议</a>
            、
            <a class="agreement-box" @click.stop="agreement(1)">隐私策略</a>
          </p>
        </div>
      </div>
    </div>
  </van-dialog>
</template>

<script lang="ts" setup>
import { Md5 } from 'ts-md5'
import { baseURL } from '../../requests'
import { AUTHORIZATION_TOKEN, REFRESH_TOKEN } from '../../constant'
import { localStorageMethods } from '../../common/storage'
import { msgLogin, pwdlogin } from '../../apis/login'
import { sendSms } from '../../apis/sms'
import { useUserStore } from '../../store/user'
import { afterLogin } from '../../requests/login'
import { authWechat, getWechatAuth } from '../../apis/wx'
import { ResponseDataType } from '../../types/api'
import { getQueryObject, removeURLParameter } from '../../requests/utils'
import { isNotEmpty } from '../../utils/common'
import { isInWx } from '../../utils/wx'
import { Ref } from 'vue'
import { showSuccess } from '@/framework/common/notify'
import { useRouterStore } from '@/framework/store/router'

const LOGIN = 'LOGIN_CAPTCHA'
const MSG_LOGIN = 'LOGIN_MSG_CODE'
const routerStore = useRouterStore()
const userStore = useUserStore()
const route = useRoute()
const loginShow = computed(() => {
  return (!userStore.getLoginState && !routerStore.getCurrentRoute.meta.public) || userStore.showLogin
})
const active = ref(0)

const captchaUrl: Ref<string> = ref('')
const showPassword: Ref<boolean> = ref(false)
const isShowSMSLogin = computed(() => {
  return active.value === 1
})
const loginPhone = ref('')
const loginUserName = ref('')
const loginPassword = ref('')
const smsCaptcha = ref('')
const imgCaptcha = ref('')

const countDown = ref(0)
let timeIntervalID: any
const sendSmsCode = () => {
  sendSms(loginPhone.value, MSG_LOGIN, imgCaptcha.value)
    .then((resp) => {
      countDown.value = resp.payload.internal
      timeIntervalID = setInterval(() => {
        countDown.value--
        if (countDown.value == 0) {
          clearInterval(timeIntervalID)
        }
      }, 1000)
      smsCaptcha.value = ''
      showSuccess('短信已发送')
    })
    .catch(() => {
      reset()
    })
}
const loginSuccessHandler = (resp: ResponseDataType) => {
  userStore.setInfo(resp.payload)
  localStorageMethods.setLocalStorage(AUTHORIZATION_TOKEN, resp.payload.accessToken)
  localStorageMethods.setLocalStorage(REFRESH_TOKEN, resp.payload.refreshToken)
  userStore.hasLogin = true
  afterLogin()
}
const reset = () => {
  loginPassword.value = ''
  smsCaptcha.value = ''
  imgCaptcha.value = ''
  updateCaptchaUrl(isShowSMSLogin.value ? MSG_LOGIN + '_CAPTCHA' : LOGIN)
}
const login = () => {
  if (isShowSMSLogin.value) {
    msgLogin(loginPhone.value, imgCaptcha.value)
      .then((resp: ResponseDataType) => loginSuccessHandler(resp))
      .catch(() => reset())
  } else {
    pwdlogin(loginUserName.value, Md5.hashStr(loginPassword.value), imgCaptcha.value)
      .then((resp: ResponseDataType) => loginSuccessHandler(resp))
      .catch(() => reset())
  }
}
const wechatLogin = () => {
  getWechatAuth(route.path).then((resp: ResponseDataType) => (window.location.href = resp.payload.url))
}
const agreement = (arg: number) => {
  console.log('agreement', arg)
}
const getCaptchaUrl = (captchaType: string) =>
  baseURL +
  '/captcha.jpg?token=' +
  localStorageMethods.getLocalStorage(AUTHORIZATION_TOKEN) +
  '&captchaType=' +
  captchaType
const updateCaptchaUrl = (captchaType: string) =>
  (captchaUrl.value = getCaptchaUrl(captchaType) + '&r=' + Math.random())
const phoneNumberRight = computed(() => {
  let value = isShowSMSLogin.value ? loginPhone.value : loginUserName.value
  // 1.1 当输入的手机号大于10位进行验证
  if (value.length > 10) {
    return /[1][3,4,5,6,7,8,9][0-9]{9}$/.test(value)
  } else {
    return true
  }
})
const captchaDisable = computed(() => {
  if (
    loginPhone.value.length > 10 &&
    phoneNumberRight.value &&
    imgCaptcha.value &&
    imgCaptcha.value.length === 4
  ) {
    return false
  } else {
    return true
  }
})
const loginValidate = computed(() => {
  if (isShowSMSLogin.value) {
    return (
      loginPhone.value.length > 10 && phoneNumberRight.value && smsCaptcha.value && smsCaptcha.value.length >= 4
    )
  } else {
    return (
      loginUserName.value &&
      phoneNumberRight.value &&
      loginPassword.value &&
      imgCaptcha.value &&
      imgCaptcha.value.length === 4
    )
  }
})
const handleTabChange = () => {
  reset()
}
onBeforeMount(() => {
  updateCaptchaUrl(LOGIN)
  if (isInWx()) {
    const { code, state } = getQueryObject(window.location.href)
    if (isNotEmpty(code) && state === 'login') {
      authWechat(code)
        .then((resp: ResponseDataType) => {
          window.location.href = removeURLParameter(window.location.href, 'code')
          loginSuccessHandler(resp)
        })
        .catch()
    } else {
      if (!userStore.hasLogin) {
        showSuccess('微信自动登录中……')
        setTimeout(() => wechatLogin(), 500)
      }
    }
  }
})
</script>

<style lang="less" scoped>
:deep(.van-field__label) {
  width: 4rem;
}

#login {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-size: contain;
  background-image: url('../../../assets/images/login/login_bg.png');

  .loginBox {
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    opacity: 0.95;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 500;

    .auth-form {
      position: relative;
      padding: 2rem;
      width: 26.5rem;
      max-width: 90%;
      font-size: 1.167rem;
      background-color: #fff;
      border-radius: 8px;
      box-sizing: border-box;
    }

    .img {
      position: absolute;
      top: 1rem;
      left: 50%;
      width: 4rem;
      transform: translate(-50%, -70%);
      z-index: 1;
      @media screen and (max-width: 320px) {
        top: 0.5rem;
        transform: translate(-50%, -40%);
        width: 5rem;
      }
    }

    .closeButton {
      position: absolute;
      right: 1rem;
      top: 0.4rem;
    }

    .verificationImage {
      display: flex;
      align-items: center;
      text-align: center; /* 水平居中文字 */
      justify-content: center; /* Flexbox方式让文字在按钮内垂直居中 */
      height: 8vw;
      width: 12vw;
    }

    .switchLogin {
      margin-top: 1rem;
      font-size: 0.78rem;
    }
  }
}

.title {
  padding: 0.5rem;
  font-size: 0.5rem;
  color: grey;
}

.agreement {
  margin-top: 1.667rem;
  line-height: 1rem;
  color: #767676;
  font-size: 0.867rem;

  .agreement-box {
    color: blue;
  }
}
</style>
